import axios from 'axios'
import router from '@/router'
import { MessageBox, Message } from 'element-ui'
import store from '@/store'
import { getToken, getRefreshToken } from '@/utils/auth'
import { localhostUrl } from './setUrl'

// 控制只显示一次重新登陆
let resetData = 1
// create an axios instance
const service = axios.create({
  // baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  baseURL: localhostUrl,
  withCredentials: true, // send cookies when cross-domain requests
  timeout: 50000 // request timeout
})

// request interceptor
service.interceptors.request.use(
  config => {
    // do something before request is sent
    if (store.getters.token) {
      // let each request carry token
      // ['X-Token'] is a custom headers key
      // please modify it according to the actual situation
      config.headers.Authorization = `Bearer ${getToken()}`
    }
    return config
  },
  error => {
    // do something with request error
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
   */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  response => {
    const res = response.data
    // // if the custom code is not 20000, it is judged as an error.
    if (res.code !== 200) {
      if (res.code === 201) {
        return res
      } else if (res.code === 421) {
        let obj = {
          token: getToken(),
          refreshToken: getRefreshToken()
        }
        // 控制只显示一次重新登陆
        if (resetData) {
          resetData = 0
        }
        // 重新获取token
        // 'http://123.183.159.70:9198/Auth/Refresh'
        axios
          .post(localhostUrl + '/Auth/Refresh', obj)
          .then(async res => {
            // 保存token
            await store.dispatch('user/resetToken', res.data.data)
            // 获取当前页面路由
            // let str = location.hash.substring(1, location.hash.length - 1)
            location.reload()
            // 刷新页面
            // router.replace(str)
          })
          .catch(err => {
            MessageBox.confirm('登录过期，是否重新登陆？', '确认退出', {
              confirmButtonText: '去登陆',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
              store.dispatch('user/removeToken').then(() => {
                location.reload()
                // 控制只显示一次重新登陆
                resetData = 1
              })
            })
          })
      } else {
        Message({
          message: res.message || 'Error',
          type: 'error',
          duration: 5 * 1000
        })

        return Promise.reject(new Error(res.message || 'Error'))
      }
    } else {
      return res
    }
  },
  error => {
    // Message({
    //   message: error.message,
    //   type: 'error',
    //   duration: 5 * 1000
    // })

    return Promise.reject(error)
  }
)

export default (url, method, data) => {
  let config = {}
  if (method.toUpperCase() === 'GET') {
    config.params = data
  } else {
    config.data = data
  }

  return service({
    url,
    method,
    ...config
  })
}
